﻿
using System;
using System.Text.RegularExpressions;


namespace JCW.Common
{
    /// <summary>
    /// 基础数据类型转换帮助类
    /// </summary>
    public static class ConvertHelper
    {

        #region 转换字符串函数
        /// <summary>
        /// 转换字符串函数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToString(object value)
        {
            if (value == null)
            {
                return "";
            }
            if (value.GetType() == typeof(byte[]))
            {
                return System.Text.Encoding.ASCII.GetString((Byte[])value, 0, ((Byte[])value).Length);
            }
            try
            {
                return value.ToString();
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 转换可空字符串函数
        /// <summary>
        /// 转换可空字符串函数（空串亦转成空）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToStringNullable(object value)
        {
            string result = ToString(value);
            if (string.IsNullOrEmpty(result))
                return null;
            else
                return result;
        }
        #endregion

        #region 转换字符串函数
        /// <summary>
        /// 转换字符串函数
        /// </summary>
        /// <param name="value"></param>
        /// <param name="replace"></param>
        /// <returns></returns>
        public static string ToString(object value, string replace)
        {
            string result = ToString(value);

            if (string.IsNullOrEmpty(result))
                return replace;
            else
                return result;
        }
        #endregion


        #region 转换时间函数
        /// <summary>
        /// 转换时间函数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(object value)
        {

            //如果为NULL
            if (value == null)
                return Convert.ToDateTime("1900-01-01 00:00:00");
            else
                try
                {
                    return Convert.ToDateTime(ToString(value));
                }
                catch
                {
                    return Convert.ToDateTime("1900-01-01 00:00:00");
                }
        }
        #endregion

        #region 转换可空时间函数
        /// <summary>
        /// 转换可空时间函数（1900-01-01 00:00:00亦转成空）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime? ToDateTimeNullable(object value)
        {
            DateTime result = ToDateTime(value);

            if (result == new DateTime(1900, 1, 1))
                return null;
            else
                return result;
        }
        #endregion


        #region 转换短整型值函数
        /// <summary>
        /// 转换短整型值函数
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>短整型值</returns>
        /// <remarks>短整型值可以表示负 ?? 至正 ?? 范围内（包括这两个数）的整数。</remarks>
        public static short ToShort(object value)
        {
            try
            {
                return Convert.ToInt16(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空短整型值函数
        /// <summary>
        /// 转换可空短整型值函数（0亦转成空）
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>短整型值</returns>
        /// <remarks>整型值可以表示负 ?? 至正 ?? 范围内（包括这两个数）的整数。</remarks>
        public static short? ToShortNullable(object value)
        {
            try
            {
                return Convert.ToInt16(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换整型值函数
        /// <summary>
        /// 转换整型值函数
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>整型值</returns>
        /// <remarks>整型值可以表示负 2,147,483,648 至正 2,147,483,647 范围内（包括这两个数）的整数。</remarks>
        public static int ToInt(object value)
        {
            try
            {
                return Convert.ToInt32(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空整型值函数
        /// <summary>
        /// 转换可空整型值函数（0亦转成空）
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>整型值</returns>
        /// <remarks>整型值可以表示负 2,147,483,648 至正 2,147,483,647 范围内（包括这两个数）的整数。</remarks>
        public static int? ToIntNullable(object value)
        {
            try
            {
                return Convert.ToInt32(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换长整型值函数
        /// <summary>
        /// 转换长整型值函数
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>长整型值</returns>
        public static long ToLong(object value)
        {
            try
            {
                return Convert.ToInt64(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空长整型值函数
        /// <summary>
        /// 转换可空长整型值函数（0亦转成空）
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>长整型值</returns>
        public static long? ToLongNullable(object value)
        {
            try
            {
                return Convert.ToInt64(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换Decimal值函数
        /// <summary>
        /// 转换整型值函数
        /// </summary>
        /// <param name="value">value</param>
        /// <returns>Decimal值</returns>
        /// <remarks>Decimal 值类型表示从正 79,228,162,514,264,337,593,543,950,335 到负 79,228,162,514,264,337,593,543,950,335 之间的十进制数。</remarks>
        public static decimal ToDecimal(object value)
        {
            try
            {
                return Convert.ToDecimal(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空Decimal值函数
        /// <summary>
        /// 转换可空整型值函数（0亦转成空）
        /// </summary>
        /// <param name="value">value</param>
        /// <returns>Decimal值</returns>
        /// <remarks>Decimal 值类型表示从正 79,228,162,514,264,337,593,543,950,335 到负 79,228,162,514,264,337,593,543,950,335 之间的十进制数。</remarks>
        public static decimal? ToDecimalNullable(object value)
        {
            try
            {
                return Convert.ToDecimal(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换单精度浮点型值函数
        /// <summary>
        /// 转换单精度浮点型值函数
        /// </summary>
        /// <param name="value">对象或null</param>
        /// <returns>单精度浮点型值</returns>
        /// <remarks>负数取值范围为 -3.4028235E+38 到 -1.401298E-45，正数取值范围为 1.401298E-45 到 3.4028235E+38</remarks>
        public static float ToFloat(object value)
        {
            try
            {
                return Convert.ToSingle(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空单精度浮点型值函数 [object]
        /// <summary>
        /// 转换可空单精度浮点型值函数 [object]
        /// </summary>
        /// <param name="value">对象或null</param>
        /// <returns>单精度浮点型值</returns>
        /// <remarks>负数取值范围为 -3.4028235E+38 到 -1.401298E-45，正数取值范围为 1.401298E-45 到 3.4028235E+38</remarks>
        public static float? ToFloatNullable(object value)
        {
            try
            {
                return Convert.ToSingle(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换双精度浮点型值函数
        /// <summary>
        /// 转换双精度浮点型值函数
        /// </summary>
        /// <param name="value">对象或null</param>
        /// <returns>双精度浮点型值</returns>
        /// <remarks>负值取值范围-1.79769313486231570E+308 到 -4.94065645841246544E-324，正值取值范围为 4.94065645841246544E-324 到 1.79769313486231570E+308</remarks>
        public static double ToDouble(object value)
        {
            try
            {
                return Convert.ToSingle(value);
            }
            catch
            {
                return 0;
            }
        }
        #endregion

        #region 转换可空双精度浮点型值函数
        /// <summary>
        /// 转换可空双精度浮点型值函数 
        /// </summary>
        /// <param name="value">对象或null</param>
        /// <returns>双精度浮点型值</returns>
        /// <remarks>负值取值范围-1.79769313486231570E+308 到 -4.94065645841246544E-324，正值取值范围为 4.94065645841246544E-324 到 1.79769313486231570E+308</remarks>
        public static double? ToDoubleNullable(object value)
        {
            try
            {
                return Convert.ToSingle(value);
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 转换逻辑值函数
        /// <summary>
        /// 转换逻辑值函数
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>逻辑值[true或flase]</returns>
        public static bool ToBool(object value)
        {
            //如果为NULL
            if (value == null)
                return false;

            switch (value.GetType().Name)
            {
                case "Int16":
                case "Int32":
                case "Int64":

                case "UInt16":
                case "UInt32":
                case "UInt64":

                case "Single":
                case "Double":
                case "Decimal":

                    if ((int)value == 0)
                        return false;
                    else
                        return true;

                case "String":
                    if (value.ToString().ToLower() == "true" || value.ToString().ToLower() == "1")
                        return true;
                    else
                        return false;

                case "Boolean":
                    return (bool)value;
                default:
                    return false;
            }
        }
        #endregion

        #region 转换可空逻辑值函数
        /// <summary>
        /// 转换可空逻辑值函数
        /// </summary>
        /// <param name="value">对象或NULL</param>
        /// <returns>逻辑值[true或flase]</returns>
        public static bool? ToBoolNullable(object value)
        {
            //如果为NULL
            if (value == null)
                return null;

            switch (value.GetType().Name)
            {
                case "Int16":
                case "Int32":
                case "Int64":

                case "UInt16":
                case "UInt32":
                case "UInt64":

                case "Single":
                case "Double":
                case "Decimal":

                    if ((int)value == 0)
                        return false;
                    else
                        return true;

                case "String":
                    if (value.ToString().ToLower() == "true" || value.ToString().ToLower() == "1")
                        return true;
                    else if (value.ToString().ToLower() == "false" || value.ToString().ToLower() == "0")
                        return false;
                    else
                        return null;

                case "Boolean":
                    return (bool)value;
                default:
                    return false;
            }
        }
        #endregion


        #region 转换GUID函数
        /// <summary>
        /// 转换GUID函数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Guid ToGuid(object value)
        {
            //如果为NULL
            if (value == null)
                return Guid.Empty;

            try
            {
                return new Guid(ToString(value));
            }
            catch
            {
                return Guid.Empty;
            }
        }
        #endregion

        #region 转换可空GUID函数
        /// <summary>
        /// 转换可空GUID函数（Guid.Empty亦转成空）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Guid? ToGuidNullable(object value)
        {
            Guid result = ToGuid(value);

            if (result == Guid.Empty)
                return null;
            else
                return result;
        }
        #endregion

        #region IPToLong  IP地址转长整型
        /// <summary>
        /// IP地址转长整型
        /// </summary>
        /// <param name="p_ip">输入ip地址 格式127.0.0.1</param>		
        /// <returns>返回转化成整型后的ip地址,格式不对则返回-1</returns>			
        public static long IPToLong(string p_ip)
        {
            string[] sitem = p_ip.Split('.');
            //长度不为4则返回-1
            if (sitem.Length != 4) return -1;
            Byte[] item = new Byte[4];
            for (int i = 0; i < sitem.Length; i++)
            {
                item[i] = Byte.Parse(sitem[i]);
            }
            long ipNum = item[3];
            ipNum |= (long)item[2] << 8;   //移位运算
            ipNum |= (long)item[1] << 16;
            ipNum |= (long)item[0] << 24;
            return ipNum;
        }
        #endregion

        #region LongToIP长整型转IP地址
        /// <summary>
        /// 长整型转IP地址
        /// </summary>
        /// <param name="p_ipNum">输入ip地址的整型格式</param>		
        /// <returns>转化成ip地址，格式127.0.0.1</returns>			
        public static string LongToIP(long p_ipNum)
        {
            long m_temp = p_ipNum;
            string m_ipStr = "";
            m_ipStr += (m_temp % 256);
            m_temp = (int)(m_temp / 256);
            for (int i = 2; i <= 4; i++)
            {
                m_ipStr = (m_temp % 256) + "." + m_ipStr;
                m_temp = (int)(m_temp / 256);
            }
            return m_ipStr;
        }
        #endregion


        #region 将时间转换成UNIX时间戳[GetStamp(DateTime dt)]
        /// <summary>
        /// 将时间转换成UNIX时间戳
        /// </summary>
        /// <param name="dt">时间</param>
        /// <returns>UNIX时间戳</returns>
        public static UInt32 ToStampFromDatetime(DateTime dt)
        {
            TimeSpan ts = dt - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            UInt32 uiStamp = Convert.ToUInt32(ts.TotalSeconds);
            return uiStamp;
        }
        #endregion



        #region 将UNIX时间戳转换成时间[GetDateTime(UInt32 uiStamp)]
        /// <summary>
        /// 将UNIX时间戳转换成时间
        /// </summary>
        /// <param name="uiStamp">UNIX时间戳</param>
        /// <returns>时间</returns>
        public static DateTime ToDatetimeFromStamp(UInt32 uiStamp)
        {
            DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddSeconds(uiStamp);
            return dt;
        }


        public static DateTime ToDatetimeFromStampStr(object strStamp)
        {
            UInt32 uiStamp = Convert.ToUInt32(strStamp);
            return ToDatetimeFromStamp(uiStamp);
        }
        #endregion


    }
}
